package com.sliansoft.wechat.attendance.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sliansoft.wechat.attendance.clientservice.ClientService;
import com.sliansoft.wechat.attendance.kit.FecthFromWeChat;

/**
 * 用户点击菜单跳转到url上时，过滤器会得到当前的用户userId和corpId。 启动tomcat的时候实例化的只是自定义filter对象的代理对象，
 * 实际的filter对象被配置成IOC中的bean，这样就可以使用IOC的依赖注入
 * 
 * @author acer
 * @date 2015年12月10日
 */
@Component
public class WhoFilter implements Filter {

	@Autowired
	private ClientService clientService;

	/**
	 * 当前的用户信息保存在session中
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String corpId = request.getParameter("state");

		if (corpId != null) {
			String access_token = clientService.getAccessTokenByCorpId(corpId);
			String code = request.getParameter("code");
			String userId = null;

			if (access_token != null && code != null) {
				userId = FecthFromWeChat.getUserId(access_token, code);
			}

			if (userId != null) {
				HttpServletRequest req = (HttpServletRequest) request;
				HttpSession session = req.getSession();
				String currentUrl = req.getRequestURL().append("?").append(req.getQueryString()).toString();
				session.setAttribute("accessToken", access_token);
				session.setAttribute("corpId", corpId);
				session.setAttribute("userId", userId);
				session.setAttribute("currentUrl", currentUrl);
				System.out.println("corpId：" + corpId);
				System.out.println("userId：" + userId);
				System.out.println("currentUrl:" + currentUrl);
			}
		}

		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// ServletContext context = fConfig.getServletContext();
		// ApplicationContext ctx =
		// WebApplicationContextUtils.getWebApplicationContext(context);
		// clientService = (ClientService) ctx.getBean("clientService");
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
